package com.sxf.service.impl;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.sxf.dao.UserDAO;
import com.sxf.domain.User;

@Service
public class UserServerImpl {
    @Resource
    private UserDAO ud;

    public void save(User user) {
        ud.save(user);
    }

    public List<User> findAll() {
        return ud.findAll();
    }

    public void findBySpecAndPaginate() {
        Page<User> page = ud.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root,
                                         CriteriaQuery<?> query, CriteriaBuilder cb) {
               // root = query.from(User.class);//不要调用,执行查询的
                Path<String> nameExp = root.get("name");
                Predicate p = cb.like(nameExp, "%Sam%");
                return p;
            }

        }, new PageRequest(0, 5, new Sort(Direction.DESC,
                new String[]{"birthday"})));

        StringBuilder stout = new StringBuilder(" 以下是姓名包含Sam人员信息 : ")
                .append("\n");
        stout.append("| 序号 | username | password | name | sex | birth |")
                .append("\n");
        int sortIndex = 1;
        for (User u : page.getContent()) {
            stout.append(" | ").append(sortIndex);
            stout.append(" | ").append(u.getName());
            stout.append(" | ").append(u.getPassword());
            stout.append(" | ").append(u.getName());
            stout.append(" | ").append(u.getSex());
            stout.append(" | ").append(u.getBirthday());
            stout.append(" | \n");
            sortIndex++;
        }
        System.err.println(stout);
    }
}
